package it.unibz.easytravel.expenses.statistic;

public class Converter {

	/**
	 * Method takes amount and converts it into integer which represents amount
	 * where one denotes 0.01 of a currency. i.e. "12.34" > 123400
	 * 
	 * @param amount
	 *            - String coming from the input field
	 * @return
	 */
	public static int convertToIntSplit(String amount) {
		int length = amount.length();
		int index = amount.indexOf(".");
		String result;

		// convert to cents
		if (index == -1) {
			result = amount += "00";
		} else {
			result = amount.substring(0, index);
			if (length - index > 2) {
				result += amount.charAt(index + 1);
				result += amount.charAt(index + 2);
			} else {
				if (length - index == 2)
					result += amount.charAt(index + 1) + "0";
			}
		}

		// add two more zeros to split the currency
		result += "00";

		return Integer.parseInt(result);
	}

	/**
	 * Method takes amount in stored in DB and converts it into float value
	 * 
	 * @param amount
	 *            - integer value in DB
	 * @return - floating point
	 */
	public static float convertToFloatMerge(int amount) {
		// drop last two digits
		amount /= 100;
		// calculate cents
		float cents = (amount % 100) / 100;
		// return the results
		return (amount - cents) / 100 + cents;
	}

	/**
	 * Gets int value an returns string representing money with 2 digits for
	 * cents
	 * 
	 * @param money
	 *            - int value stored in DB
	 * @return - String representation, floating point representation
	 */
	public static String convertToStringMerge(int amount) {
		// drop last two digits
		amount /= 100;
		// calculate cents
		int cents = Math.abs(amount % 100);
		String cents_s;
		if (cents == 0) {
			cents_s = "00";
		} else {
			cents_s = Integer.toString(cents);
		}
		// return the results
		if (amount == 0)
			return "0.00";
		if (amount > 0) {
			return (amount - cents) / 100 + "." + cents_s;
		} else {
			return (amount + cents) / 100 + "." + cents_s;
		}
	}

}
